# -*- coding: UTF-8 -*-
import getopt
import json
import os
import sys

import requests
import threadpool


class Attence:
    def __init__(self, id, taken=None, thread_num=20):
        self.taken = taken
        self.id = id
        self.thread_num = thread_num
        self.session = requests.Session()
        if taken is None:
            with open('ktpdata.json', 'r', encoding="utf-8") as json_file:
                ktpdata = json.load(json_file)
                self.taken = ktpdata.get('taken')

    def deal_attence(self):
        pool = threadpool.ThreadPool(self.thread_num)
        tasks = threadpool.makeRequests(self.attence_post, [i for i in range(10000)])
        [pool.putRequest(task) for task in tasks]
        pool.wait()  # 等所有任务结束

    def attence_post(self, i=0):
        url = 'https://jmuopenapi.ketangpai.com/AttenceApi/checkin'
        postda = {"id": self.id, "code": str(i).zfill(4), "latitude": "", "longitude": "", "accuracy": "", "token": self.taken,
                  "appid": ""}
        resp = self.post(url, postda)
        # print(resp)
        if resp.get('state') == 1:
            print(("OK! Attendance code:"+postda['code']).encode('gbk'))
            os._exit(0)

    def post(self, url, data):
        for i in range(3):
            try:
                r = self.session.post(url, data)
                return r.json()
            except requests.exceptions.ConnectionError as e:
                print(("Error:" + str(e)).encode('gbk'))
            except json.JSONDecodeError as e:
                print(("Error:" + str(e)).encode('gbk'))


if __name__ == "__main__":
    taken = None
    id = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ht:i:", ["taken=", "id="])
    except getopt.GetoptError:
        print('test.py -t <taken> -i <id>'.encode('gbk'))
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -t <taken> -i <id>>'.encode('gbk'))
            sys.exit()
        elif opt in ("-t", "--taken"):
            taken = arg
        elif opt in ("-i", "--id"):
            id = arg
    attence = Attence(id, taken)
    attence.deal_attence()

'''
time_start = time.time()
cmd = "python deal_attence.py -t {} -i {}".format(self.taken, attence['id'])
print(cmd)
ret = os.popen(cmd).read()
print(ret)
time_end = time.time()
print('耗时：', time_end - time_start, 's')
'''